package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.Common;
import com.ruoyi.common.utils.ExcelUtil;
import com.ruoyi.common.utils.ReadExcelUtil;
import com.ruoyi.common.utils.excelUtil.ExcelReaderUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ExcelLogService;
import com.ruoyi.system.service.PhoneService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 微信 业务层处理
 * 
 * @author admin
 */
@Service
public class PhoneServiceImpl implements PhoneService {

	private static final Logger LOGGER = LoggerFactory.getLogger(PhoneServiceImpl.class);

	private ReadExcelUtil<String> util = new ReadExcelUtil<String>();

	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private PhoneMapper phoneMapper;
	@Autowired
	private PhoneLabelMapper phoneLabelMapper;

	@Autowired
	private ExcelLogService excelLogService;

	@Autowired
	private ExcelLogMapper excelLogMapper;


	/**
	 * 根据条件分页查询微信号数据
	 *
	 * @return 微信号数据集合信息
	 */
	@Override
	@DataScope(tableAlias = "u")
	public List<Phone> selectPhoneList(Phone phone) {
		return phoneMapper.selectPhoneList(phone);
	}


	public List<Phone> selectPhoneData(Phone phone) {
		return phoneMapper.selectPhoneData(phone);
	}
	/**
	 *
	 * @param phoneLabel
	 * @return
	 */
	@Override
	@DataScope(tableAlias = "u")
	public List<PhoneLabel> selectPhoneLabelList(PhoneLabel phoneLabel) {
		return phoneLabelMapper.selectPhoneLabelList(phoneLabel);
	}

	@Override
	public List<PhoneLabel> selectPhoneLabelData(PhoneLabel phoneLabel) {
		return phoneLabelMapper.selectPhoneLabelData(phoneLabel);
	}


	@Override
	public int insertPhone(Phone phone){
		return phoneMapper.insertPhone(phone);
	}

	@Override
	public int insertBatchPhone(List<Phone> phones){
		if(phones.size() > 0)
			return phoneMapper.insertBatchPhone(phones);
		return Constants.TOAJAX_FAIL;
	}

	@Override
	public int insertPhoneLabel(PhoneLabel phoneLabel){
		return phoneLabelMapper.insertPhoneLabel(phoneLabel);
	}

	@Override
	public Phone getEntityByPhone(String phone){
		Phone pho = new Phone();
		pho.setPhone(Long.valueOf(phone));
		return phoneMapper.getEntityByPhone(pho);
	}

	@Override
	public PhoneLabel getEntityById(Long id){
		PhoneLabel phL = new PhoneLabel();
		phL.setId(id);
		return phoneLabelMapper.getEntity(phL);
	}

	/**
	 * 大批量数据导入
	 * @param path
	 * @param originalFilename
	 *
	 * 这里导入的数据重复的不做处理（处理的话 导致导入数据时间变长）
	 */
	public void writeExcelLargeData(String path,String originalFilename) throws Exception{

		List<Phone> phones = new ArrayList<>(); // 要添加的数据集
		//List<Phone> phonesRepeat = new ArrayList<>();// 要更新的数据集

		List<String> datas = ExcelReaderUtil.readExcel(path);
		// 文件名（去除后缀）
		String allFileName = ExcelUtil.allFileName(originalFilename);

		if(datas.size() > 0){
			// 添加到文件导入日志
			excelLogService.insertExcelLog(originalFilename,0,datas.size());
			for(String str : datas){
				Phone phone = new Phone();
				phone.setPhone(Long.valueOf(str));
				phone.setFlag(","+allFileName+","); // 默认给个 ，(导入的文件名作为首个标签)
				phones.add(phone); // 添加到 phones
			}
			// 批量插入
			this.insertBatchPhone(phones);

		}
	}

	/**
	 * 数据导入（普通导入 数据量不超过万行）
	 * @param in
	 */
	@Override
	public void writeExelData(InputStream in,String originalFilename){
		try{
			List<String> datas = new ArrayList<>();
			List<Phone> phones = new ArrayList<>();
			List<Phone> phonesRepeat = new ArrayList<>();//重复的数据

			// 文件后缀名
			String postfix = ExcelUtil.postfix(originalFilename);
			// 文件名（去除后缀）
			String allFileName = ExcelUtil.allFileName(originalFilename);

			if(Common.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) datas = util.readXls(in);
			else datas = util.readXlsx(in);

			if(datas.size() > 0){
				int excelNum = datas.size()-1; // 去除第一行的数目
				// 添加到文件导入日志
				excelLogService.insertExcelLog(originalFilename,0,excelNum);

				for(String str : datas){
					String[] strs = str.split("ぁ");

					// 第一行就是电话
					if(StringUtils.isNotEmpty(strs[0])){
						Phone phone = new Phone();
						// 是否重复
						if(this.getEntityByPhone(strs[0]) == null ){ // 为空 才插入数据
							phone.setPhone(Long.valueOf(strs[0]));
							phone.setFlag(","+allFileName+","); // 默认给个 ，(导入的文件名作为首个标签)
							phones.add(phone); // 添加到 phones

						}else{ // 重复的数据 直接添加上标签
							phone = this.getEntityByPhone(strs[0]);
							phonesRepeat.add(phone);
						}
					}
				}
				// 批量插入
				this.insertBatchPhone(phones);

				// 批量更新标签(重复的数据)
				String flags = allFileName+",";
				this.updateBatchFlag(flags,phonesRepeat);
			}
		}catch (Exception e){e.printStackTrace();}

	}

	@Override
	public int updatePhone(Phone phone){
		return phoneMapper.updatePhone(phone);
	}

	@Override
	public void updateBatchFlag(String flags,List<Phone> phone){
		if(phone.size() > 0){
			Phones phones = new Phones();
			phones.setFlags(flags);
			phones.setIds(phone);
			phoneMapper.updateBatchFlag(phones);
		}
	}
	/**
	 * 更新标签
	 * @param phoneLabel
	 * @return 结果
	 */
	@Override
	public int updatePhoneLabel(PhoneLabel phoneLabel){
		return phoneLabelMapper.updatePhoneLabel(phoneLabel);
	}

	public int removePhoneLabel(String ids){
		Long[] ids_ = Convert.toLongArray(ids);
		return phoneLabelMapper.deletePhoneLabelByIds(ids_);
	}

	/**
	 * 整理数据
	 */
	@Override
	public void arrangeDatas(){
		// 查找出重复的数据集
		List<Phone> phoneRepeatDatas = phoneMapper.getRepeatPhoneData();
		if(phoneRepeatDatas.size()>0){
			// 批量删除重复数据

		}
	}

	public int removePhoneByFlag(String flag,Long id){
		Phone phone = new Phone();
		phone.setFlag(flag);
		phoneMapper.deletePhone(phone);
		// 删除日志
		ExcelLog excelLog = new ExcelLog();
		excelLog.setId(id);
		return excelLogMapper.deleteExcelLog(excelLog);
	}

}
